﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using DataBaseLibrary.DBInterfaces;
using DataBaseLibrary.DBObjectsFB;


namespace DocMreoLiteVersion
{
    /// <summary>
    /// Interaction logic for FormChoiseDocument.xaml
    /// </summary>
    public partial class FormChoiseDocument : UserControl
    {

        //Описание событий

        /// <summary>
        /// Событие вывода истории создания документов
        /// </summary>
        delegate void CreateHistoryDocumentsEventHandler(object sender, RoutedEventArgs args);
        public static readonly RoutedEvent CreateHistoryDocumentsEvent = EventManager.RegisterRoutedEvent("CreateHistoryDocuments", RoutingStrategy.Bubble, typeof(CreateHistoryDocumentsEventHandler), typeof(FormChoiseDocument));

        public event RoutedEventHandler CreateHistoryDocuments
        {
            add { AddHandler(CreateHistoryDocumentsEvent, value); }
            remove { RemoveHandler(CreateHistoryDocumentsEvent, value); }
        }

        /// <summary>
        /// Поиск документа в истории создания. И добавления его в лист. Какой документ искать - определяется по номеру
        /// </summary>
        public static readonly RoutedEvent SearchDocFromNumberEvent = EventManager.RegisterRoutedEvent("SearchDocFromNumber", RoutingStrategy.Bubble, typeof(CreateHistoryDocumentsEventHandler), typeof(FormChoiseDocument));

        public event RoutedEventHandler SearchDocFromNumber
        {
            add { AddHandler(SearchDocFromNumberEvent, value); }
            remove { RemoveHandler(SearchDocFromNumberEvent, value); }
        }


        /// <summary>
        /// Событие. Открывает выбранный документ под двойному щелчку
        /// </summary>
        public static readonly RoutedEvent DocumentOpenEventEvent = EventManager.RegisterRoutedEvent("DocumentOpenEvent", RoutingStrategy.Bubble, typeof(CreateHistoryDocumentsEventHandler), typeof(FormChoiseDocument));

        public event RoutedEventHandler DocumentOpenEvent
        {
            add { AddHandler(DocumentOpenEventEvent, value); }
            remove { RemoveHandler(DocumentOpenEventEvent, value); }
        }

        public FormChoiseDocument()
        {
            InitializeComponent();
        }


        public IDBObject GetDbObjectFromListBox()
        {
            try
            {
                IDBObject item = ListBoxDocuments.SelectedItem as IDBObject;
                if (item == null)
                    throw new NullReferenceException("Не существует объекта IDBObject");
                return ListBoxDocuments.SelectedItem as IDBObject;
            }
            catch (Exception )
            {                
                throw new SystemException("В списке не существует документов или ни один документ не был выбран!");
            }
        }

        public void AddDbObjectListBox(IDBObject item)
        {
            foreach (var obj in ListBoxDocuments.Items)
            {                
                if ((obj as DBFObject).GetID().Equals((item as DBFObject).GetID()))
                    return;
            }
            ListBoxDocuments.Items.Insert(0, item);
        }

        private void ButtonHistoryDocs(object sender, RoutedEventArgs e)
        {
            if (MainWindow.session.user.GetPrivelegies() == User.Privelegies.Operator)
            {
                MessageBox.Show(
                    "У Вас не достаточно прав для выполнения данных действий. \n Обратитесь к администратору!");
                return;
            }
            RoutedEventArgs args = new RoutedEventArgs(FormChoiseDocument.CreateHistoryDocumentsEvent);
            RaiseEvent(args);            
        }

        //Найти договор по номеру и добавить в листбокс
        private void SearchDocListDocs(object sender, RoutedEventArgs e)
        {
            if (NumberDocumentTextBox.Text == String.Empty)
            {
                MessageBox.Show("Введите номер документа");
                return;
            }
            RoutedEventSearchDocArgs args = new RoutedEventSearchDocArgs(FormChoiseDocument.SearchDocFromNumberEvent);
            args.NumberDocument = NumberDocumentTextBox.Text;
            RaiseEvent(args);
        }

        //Загрузка выделенного айтема
        private void ListBoxDocuments_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (ListBoxDocuments.SelectedItem != null)
            {
                if (ListBoxDocuments.SelectedItem as DBFObject != null)
                {
                    RoutedEventSearchDocArgs args = new RoutedEventSearchDocArgs(FormChoiseDocument.DocumentOpenEventEvent);
                    args.NumberDocument = (ListBoxDocuments.SelectedItem as DBFObject).GetID().ToString();
                    RaiseEvent(args);
                }
            }
        }

        private void CloseButton_OnClick(object sender, RoutedEventArgs e)
        {
            System.Windows.Application.Current.MainWindow.Close();
        }
    }


    public class RoutedEventSearchDocArgs : RoutedEventArgs
    {
        public RoutedEventSearchDocArgs(RoutedEvent _event) : base(_event) { }
        public String NumberDocument  = null;

    }

}
